package com.ds.lens.collector.receive.handler;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ds.lens.collector.receive.kafka.KafkaProducer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

/**
 * @author ethan
 * @author WeiShaoying
 */
@Service
@Slf4j
public class MetricsHandler extends AbstractHandler {

    @Autowired
    private KafkaProducer kafkaProducer;

    @Value("${spring.kafka.metrics.topic}")
    private String metricsTopic;

    @Override
    public HandlerResultWrapper handleData(String metrics, RequestInfo requestInfo) {
        try {
            JSONObject metricsObj = JSON.parseObject(metrics);
            metricsObj.put("appKey",requestInfo.getAppKey());
            metricsObj.put("appId",requestInfo.getAppId());
            kafkaProducer.sendMessage(metricsTopic, metricsObj.toString());
            HandlerResultWrapper handlerResultWrapper = new HandlerResultWrapper();
            handlerResultWrapper.setResult("OK");
            return handlerResultWrapper;
        } catch (Exception e) {
            log.warn("metrics handle error. Caused:{}. Metric:{}", e.getMessage(), e);
        }
        return null;
    }
}
